package cn.wolfcode.wolf2w.resolver;


import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户参数解析器
 *
 * 将请求映射方法中的 userinfo类型的参数 解析成当前登录用户对象 并注入
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    /**
     * 支持的解析类型
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(
            MethodParameter parameter) {

        return parameter.getParameterType() == UserInfo.class && parameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * 当解析类型支持时 才会执行该方法
     * 执行具体的解析逻辑 解析UserInfo类型的参数 获取当前登录的用户信息 并注入
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(
            MethodParameter parameter,
            ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest,
            WebDataBinderFactory binderFactory)
            throws Exception {

        // 获取token
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");

        // 查到用户对象 返回
        return userInfoRedisService.getUserByToken(token);
    }
}
